<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="应用名称" prop="appName">
        <el-input
          v-model="queryParams.appName"
          placeholder="请输入应用名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="应用ID" prop="appId">
        <el-input
            v-model="queryParams.appId"
            placeholder="请输入应用ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:app:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:app:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:app:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="应用ID" align="center" prop="appId" />
      <el-table-column label="应用名称" align="center" prop="appName" />
      <el-table-column label="状态" align="center" prop="status" >
        <template #default="scope">
          <span>{{ scope.row.status == 1 ? '正常' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template #default="scope">
          <el-button link type="primary" icon="Document" @click="handleDetail(scope.row)" v-hasPermi="['system:app:query']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:app:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:app:remove']">删除</el-button>
          <el-button link type="warning" icon="Connection" @click="handlePushUserData(scope.row)" v-hasPermi="['system:app:pushData']">推送用户数据</el-button>
          <el-button link type="warning" icon="Connection" @click="handlePushDeptData(scope.row)" v-hasPermi="['system:app:pushData']">推送部门数据</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改应用对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="appRef" :model="form" :rules="rules" :disabled="isShowDetail" label-width="140px" >
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="form.appName" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="公钥" prop="publicKey">
          <el-input v-model="form.publicKey" type="textarea" placeholder="请输入符合RSA规范的公钥" />
        </el-form-item>
        <el-form-item label="私钥" prop="privateKey">
          <el-input v-model="form.privateKey" type="textarea" placeholder="请输入符合RSA规范的私钥" />
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" plain @click="generateAppSecret">随机生成密钥</el-button>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option label="正常" :value="1"/>
            <el-option label="禁用" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="推送数据" prop="pushDataTypes">
          <el-checkbox-group v-model="form.pushDataTypes">
            <el-checkbox label="user">用户</el-checkbox>
            <el-checkbox label="dept">部门</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="推送数据URL" prop="pushUserUrl">
          <el-input v-model="form.pushDataUrl" type="textarea" placeholder="请输入推送数据URL" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="App">
import { listApp, getApp, delApp, addApp, updateApp, pushUserData, pushDeptData, generateKeyPair } from "@/api/system/app";
import { uuid } from "@/utils/tools"

const { proxy } = getCurrentInstance();

const appList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isShowDetail = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appId: null,
    appName: null,
    status: null,
  },
  rules: {
    appName: [
      { required: true, message: "应用名称不能为空", trigger: "blur" },
      { min: 2, max: 100, message: '应用名称长度为2至100个字符', trigger: 'blur' }
    ],
    appSecret: [
      { required: true, message: "应用秘钥不能为空", trigger: "blur" },
      { min: 32, max: 256, message: '应用秘钥长度为32至256个字符', trigger: 'blur' }
    ],
    status: [
      { required: true, message: "请选择状态", trigger: "change" }
    ],
    publicKey: [
      { required: true, message: "公钥不能为空", trigger: "blur" }
    ],
    privateKey: [
      { required: true, message: "私钥不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询应用列表 */
function getList() {
  loading.value = true;
  listApp(queryParams.value).then(response => {
    appList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    appId: null,
    appName: null,
    publicKey: null,
    privateKey: null,
    status: null,
    pushDataType: null,
    pushDataTypes: [],
    pushDataUrl: null,
    remark: null
  };
  proxy.resetForm("appRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.appId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isShowDetail.value = false
  open.value = true;
  title.value = "添加应用";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  isShowDetail.value = false
  const _appId = row.appId || ids.value
  getApp(_appId).then(response => {
    let data = response.data;
    if (response.data.pushDataType) {
      let pushDataTypes = response.data.pushDataType.split(",")
      data.pushDataTypes = pushDataTypes
    } else {
      data.pushDataTypes = []
    }
    form.value = data
    open.value = true;
    title.value = "修改应用";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["appRef"].validate(valid => {
    if (valid) {
      if (form.value.pushDataTypes && form.value.pushDataTypes.length > 0) {
        form.value.pushDataType = form.value.pushDataTypes.join(",");
      }
      if (form.value.appId != null) {
        updateApp(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addApp(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _appIds = row.appId || ids.value;
  proxy.$modal.confirm('是否确认删除应用【' + row.appName + '】数据？').then(function() {
    return delApp(_appIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 推送用户数据 */
function handlePushUserData(row) {
  proxy.$modal.confirm('是否为应用【' + row.appName + '】全量推送用户数据？').then(function() {
    return pushUserData(row.appId);
  }).then(() => {
    proxy.$modal.msgSuccess("开始推送，具体结果可在数据推送记录中查看");
  }).catch(() => {});
}

/** 推送部门数据 */
function handlePushDeptData(row) {
  proxy.$modal.confirm('是否为应用【' + row.appName + '】全量推送部门数据？').then(function() {
    return pushDeptData(row.appId);
  }).then(() => {
    proxy.$modal.msgSuccess("开始推送，具体结果可在数据推送记录中查看");
  }).catch(() => {});
}

/** 详情按钮操作 */
function handleDetail(row) {
  reset();
  isShowDetail.value = true
  const _appId = row.appId
  getApp(_appId).then(response => {
    form.value = response.data;
    if (response.data.pushDataType) {
      let pushDataTypes = response.data.pushDataType.split(",")
      form.value.pushDataTypes = pushDataTypes
    }
    open.value = true;
    title.value = "应用详情";
  });
}

/**
 * 随机生成密钥
 */
function generateAppSecret() {
  generateKeyPair().then(response => {
      form.value.publicKey = response.data.publicKey
      form.value.privateKey = response.data.privateKey
  });
}
getList();
</script>
